package com.lh.pospi.x_store.ui;

import android.Manifest;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.itheima.retrofitutils.HttpHelper;
import com.itheima.retrofitutils.ItheimaHttp;
import com.itheima.retrofitutils.Request;
import com.itheima.retrofitutils.listener.HttpResponseListener;
import com.lany.sp.SPHelper;
import com.lh.pospi.x_store.R;
import com.lh.pospi.x_store.app.MyApp;
import com.lh.pospi.x_store.base.BaseActivity;
import com.lh.pospi.x_store.modle.BnnerBean;
import com.lh.pospi.x_store.modle.GoodsBean;
import com.lh.pospi.x_store.modle.MarktBean;
import com.lh.pospi.x_store.modle.RequestGoods;
import com.lh.pospi.x_store.modle.RequestMark;
import com.lh.pospi.x_store.modle.TestBean;
import com.lh.pospi.x_store.modle.UserBean;
import com.lh.pospi.x_store.utils.Constant;
import com.lh.pospi.x_store.utils.DBService;
import com.lh.pospi.x_store.utils.DownHelper;
import com.lh.pospi.x_store.utils.LoadingUtil;
import com.lh.pospi.x_store.view.ProgressDialog;
import com.lh.pospi.x_store.view.RxEdite2Dialog;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton;
import com.vondear.rxtool.RxActivityTool;
import com.vondear.rxtool.RxAnimationTool;
import com.vondear.rxtool.RxBarTool;
import com.vondear.rxtool.RxKeyboardTool;
import com.vondear.rxtool.RxLogTool;
import com.vondear.rxtool.RxPermissionsTool;
import com.vondear.rxtool.RxSPTool;
import com.vondear.rxtool.view.RxToast;
import com.vondear.rxui.activity.AndroidBug5497Workaround;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class LoginActivity extends FragmentActivity {
    @BindView(R.id.logo)
    ImageView mLogo;
    @BindView(R.id.et_mobile)
    EditText mEtMobile;
    @BindView(R.id.iv_clean_phone)
    ImageView mIvCleanPhone;
    @BindView(R.id.et_password)
    EditText mEtPassword;
    @BindView(R.id.clean_password)
    ImageView mCleanPassword;
    @BindView(R.id.iv_show_pwd)
    ImageView mIvShowPwd;
    @BindView(R.id.btn_login)
    QMUIRoundButton mBtnLogin;
    @BindView(R.id.regist)
    TextView mRegist;
    @BindView(R.id.forget_password)
    TextView mForgetPassword;
    @BindView(R.id.content)
    LinearLayout mContent;
    @BindView(R.id.scrollView)
    NestedScrollView mScrollView;
    @BindView(R.id.service)
    LinearLayout mService;
    @BindView(R.id.root)
    RelativeLayout mRoot;
    private int screenHeight = 0;//屏幕高度
    private int keyHeight = 0; //软件盘弹起后所占高度
    private float scale = 0.6f; //logo缩放比例
    private int height = 0;
    private LoadingUtil util;
    private RxEdite2Dialog edite2Dialog;
    private Activity mContext;
    private List<UserBean> userBeans;
    private ProgressDialog dialog;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        RxBarTool.setTransparentStatusBar(this);//状态栏透明化
        RxBarTool.StatusBarLightMode(mContext);
        if (isFullScreen(this)) {
            AndroidBug5497Workaround.assistActivity(this);
        }
        util = new LoadingUtil(mContext);

        init();
    }

    private void init() {
        RxPermissionsTool.with(this)
                .addPermission(Manifest.permission.ACCESS_FINE_LOCATION)
                .addPermission(Manifest.permission.ACCESS_COARSE_LOCATION)
                .addPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
                .addPermission(Manifest.permission.CAMERA)
                .addPermission(Manifest.permission.CALL_PHONE)
                .addPermission(Manifest.permission.READ_PHONE_STATE).initPermission();
        initView();
        initEvent();
        initData();
        mEtMobile.setText(SPHelper.getInstance().getString(Constant.LOGIN_NAME));
        mEtPassword.setText(SPHelper.getInstance().getString(Constant.LOGIN_PWD));

    }

    private void initData() {

        if (SPHelper.getInstance().getString(Constant.DB_IP).isEmpty() || SPHelper.getInstance().getString(Constant.DB_NAME).isEmpty()) {
            edite2Dialog = new RxEdite2Dialog(mContext);
            edite2Dialog.setCancelable(false);
            edite2Dialog.setSureOnclickLister(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    RxKeyboardTool.hideSoftInput(mContext);
                    if (edite2Dialog.getEt1Msg().isEmpty() || edite2Dialog.getEt2Msg().isEmpty()) {
                        RxToast.error("请填写完整");
                    } else {
                        SPHelper.getInstance().putString(Constant.DB_IP, edite2Dialog.getEt1Msg());
                        SPHelper.getInstance().putString(Constant.DB_NAME, edite2Dialog.getEt2Msg());
                        edite2Dialog.dismiss();
                        connect();
                    }

                }
            });
            edite2Dialog.setCancleOnclickLister(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    RxKeyboardTool.hideSoftInput(mContext);
//                    RxActivityTool.finishAllActivity();
                    finish();
                }
            });
            edite2Dialog.show();
        }
    }

    private void initView() {
        screenHeight = this.getResources().getDisplayMetrics().heightPixels; //获取屏幕高度
        keyHeight = screenHeight / 3;//弹起高度为屏幕高度的1/3
    }

    private void initEvent() {
        mEtMobile.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!TextUtils.isEmpty(s) && mIvCleanPhone.getVisibility() == View.GONE) {
                    mIvCleanPhone.setVisibility(View.VISIBLE);
                } else if (TextUtils.isEmpty(s)) {
                    mIvCleanPhone.setVisibility(View.GONE);
                }
            }
        });
        mEtPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!TextUtils.isEmpty(s) && mCleanPassword.getVisibility() == View.GONE) {
                    mCleanPassword.setVisibility(View.VISIBLE);
                } else if (TextUtils.isEmpty(s)) {
                    mCleanPassword.setVisibility(View.GONE);
                }
                if (s.toString().isEmpty()) {
                    return;
                }
                if (!s.toString().matches("[A-Za-z0-9]+")) {
                    String temp = s.toString();
                    Toast.makeText(mContext, "请输入数字或字母", Toast.LENGTH_SHORT).show();
                    s.delete(temp.length() - 1, temp.length());
                    mEtPassword.setSelection(s.length());
                }
            }
        });
        /**
         * 禁止键盘弹起的时候可以滚动
         */
        mScrollView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });
        mScrollView.addOnLayoutChangeListener(new ViewGroup.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
              /* old是改变前的左上右下坐标点值，没有old的是改变后的左上右下坐标点值
              现在认为只要控件将Activity向上推的高度超过了1/3屏幕高，就认为软键盘弹起*/
                if (oldBottom != 0 && bottom != 0 && (oldBottom - bottom > keyHeight)) {
                    Log.e("wenzhihao", "up------>" + (oldBottom - bottom));
                    int dist = mContent.getBottom() - bottom;
                    if (dist > 0) {
                        ObjectAnimator mAnimatorTranslateY = ObjectAnimator.ofFloat(mContent, "translationY", 0.0f, -dist);
                        mAnimatorTranslateY.setDuration(300);
                        mAnimatorTranslateY.setInterpolator(new LinearInterpolator());
                        mAnimatorTranslateY.start();
                        RxAnimationTool.zoomIn(mLogo, 0.6f, dist);
                    }
                    mService.setVisibility(View.INVISIBLE);

                } else if (oldBottom != 0 && bottom != 0 && (bottom - oldBottom > keyHeight)) {
                    Log.e("wenzhihao", "down------>" + (bottom - oldBottom));
                    if ((mContent.getBottom() - oldBottom) > 0) {
                        ObjectAnimator mAnimatorTranslateY = ObjectAnimator.ofFloat(mContent, "translationY", mContent.getTranslationY(), 0);
                        mAnimatorTranslateY.setDuration(300);
                        mAnimatorTranslateY.setInterpolator(new LinearInterpolator());
                        mAnimatorTranslateY.start();
                        //键盘收回后，logo恢复原来大小，位置同样回到初始位置
                        RxAnimationTool.zoomOut(mLogo, 0.6f);
                    }
                    mService.setVisibility(View.VISIBLE);
                }
            }
        });

    }

    public boolean isFullScreen(Activity activity) {
        return (activity.getWindow().getAttributes().flags &
                WindowManager.LayoutParams.FLAG_FULLSCREEN) == WindowManager.LayoutParams.FLAG_FULLSCREEN;
    }

    @OnClick({R.id.iv_clean_phone, R.id.clean_password, R.id.iv_show_pwd ,R.id.btn_login,R.id.regist,R.id.forget_password})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_clean_phone:
                mEtMobile.setText("");
                break;
            case R.id.clean_password:
                mEtPassword.setText("");
                break;
            case R.id.iv_show_pwd:
                if (mEtPassword.getInputType() != InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) {
                    mEtPassword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                    mIvShowPwd.setImageResource(R.drawable.pass_visuable);
                } else {
                    mEtPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    mIvShowPwd.setImageResource(R.drawable.pass_gone);
                }
                String pwd = mEtPassword.getText().toString();
                if (!TextUtils.isEmpty(pwd))
                    mEtPassword.setSelection(pwd.length());
                break;
            case R.id.btn_login:
                userBeans = MyApp.getInstance().getDaoSession().getUserBeanDao().loadAll();
                RxKeyboardTool.hideSoftInput(mContext);
                login();


                break;
            case R.id.regist://参数设置
                initPramsDialog();

                break;
            case R.id.forget_password:
                connect();
                break;
        }
    }

    private void login() {
//        connectDb();

        String name = mEtMobile.getText().toString().trim();
        String pwd = mEtPassword.getText().toString().trim();
        if (name.isEmpty()) {
            RxToast.warning("用户名不能为空");
            return;
        }
        if (pwd.isEmpty()) {
            RxToast.warning("密码不能为空");
            return;
        }

        if (userBeans.size() == 0) {
            RxToast.warning("用户信息未下载");
            return;
        }
        boolean isRight = false;
        for (UserBean bean : userBeans) {
            if (bean.getCode().equals(name)&&bean.getCode().equals(pwd)) {
                SPHelper.getInstance().putString(Constant.LOGIN_NAME, name);
                SPHelper.getInstance().putString(Constant.LOGIN_PWD,pwd);
                isRight = true;
                MyApp.getInstance().setmUserBean(bean);
                startActivity(new Intent(this, MainActivity.class));
                break;
            }
        }
        if (!isRight) {
            RxToast.error("用户名或密码错误");
        } else {
            finish();
        }
    }

    private void initPramsDialog() {
        final RxEdite2Dialog edite2Dialog = new RxEdite2Dialog(mContext);
        edite2Dialog.setTitle("参数修改");
        edite2Dialog.setCancelable(false);
        edite2Dialog.setCancleBtText("取消");
        edite2Dialog.setEt1Text(SPHelper.getInstance().getString(Constant.DB_IP));
        edite2Dialog.setEt2Text(SPHelper.getInstance().getString(Constant.DB_NAME));
        edite2Dialog.setSureOnclickLister(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (edite2Dialog.getEt1Msg().isEmpty() || edite2Dialog.getEt2Msg().isEmpty()) {
                    RxToast.error("请填写完整");
                } else {
//                    HttpHelper.setBaseUrl("http://" + edite2Dialog.getEt1Msg());
                    RxLogTool.d("http://" + edite2Dialog.getEt1Msg());
                    SPHelper.getInstance().putString(Constant.DB_IP, edite2Dialog.getEt1Msg());
                    SPHelper.getInstance().putString(Constant.DB_NAME, edite2Dialog.getEt2Msg());
                    edite2Dialog.dismiss();
//                    ItheimaHttp.init(mContext,);
                    connect();
                }

            }
        });
        edite2Dialog.setCancleOnclickLister(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                edite2Dialog.dismiss();
            }
        });
        edite2Dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                RxKeyboardTool.toggleSoftInput(mContext, edite2Dialog.getEt1());
            }
        });
        edite2Dialog.show();
        RxKeyboardTool.toggleSoftInput(mContext, edite2Dialog.getEt1());
    }

    /**
     * http://139.199.121.126
     */
    int pro = 0;
    private void connect(){

        dialog = new ProgressDialog(mContext);
        dialog.setProgress(0);
        dialog.setCancelable(false);
        dialog.show();
        DownHelper helper = new DownHelper();
        helper.getGoodsSize(new DownHelper.CountLister() {
            @Override
            public void getCount(int count) {
                if (count > 0) {
                    dialog.setMax(count);
                    upPro(dialog,count);
                } else {
                    RxToast.error("请求失败,请检查配置");
                    dialog.dismiss();
                }

            }
        });

//        helper.downGoods();
//        helper.downStock();
//        helper.downUser();
//        helper.downMark();
//        helper.downCus();
//        helper.downSup();
//        helper.downBrand();
//        helper.downCat();
    }
    private void upPro(final ProgressDialog dialog, final int max) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (pro <max) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            dialog.setProgress(pro);
                        }
                    });
                    pro+=400;
                    try {
                        Thread.sleep(1400);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                dialog.dismiss();
                pro = 0;


            }
        }).start();
    }

    private void connectDb() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                DBService.getDbService().saveGoods();
            }
        }).start();
    }



}